import { Fragment, type ReactNode, useId } from 'react'
import { Menu, Transition } from '@headlessui/react'
import { EllipsisHorizontalIcon } from '@heroicons/react/24/outline'
import clsx from 'clsx'

export type MenuItem = {
  label: string
  onSelect: () => void
  danger?: boolean
  icon?: ReactNode
}

export const KebabMenu = ({ items, className, buttonRef }: { items: MenuItem[]; className?: string; buttonRef?: React.Ref<HTMLButtonElement> }) => {
  const id = useId()
  return (
    <Menu as="div" className={clsx('relative inline-block text-left', className)}>
      <Menu.Button
        ref={buttonRef}
        className="rounded-full p-1.5 text-slate-500 transition hover:bg-slate-100 focus:outline-none focus-visible:ring-2 focus-visible:ring-blush-200"
        onClick={(event) => event.stopPropagation()}
      >
        <EllipsisHorizontalIcon className="h-5 w-5" aria-hidden="true" />
        <span className="sr-only">更多</span>
      </Menu.Button>
      <Transition
        as={Fragment}
        enter="transition ease-out duration-100"
        enterFrom="transform opacity-0 scale-95"
        enterTo="transform opacity-100 scale-100"
        leave="transition ease-in duration-75"
        leaveFrom="transform opacity-100 scale-100"
        leaveTo="transform opacity-0 scale-95"
      >
        <Menu.Items className="absolute right-0 z-50 mt-2 max-h-[calc(100vh-4rem)] max-w-[calc(100vw-2rem)] origin-top-right overflow-auto rounded-2xl border border-slate-200/70 bg-white p-1 text-sm shadow-xl focus:outline-none">
          {items.map((item, idx) => (
            <Menu.Item key={`${id}-${idx}`}>
              {({ active }) => (
                <button
                  type="button"
                  className={clsx(
                    'flex w-full items-center gap-2 rounded-xl px-3 py-2 text-left font-medium',
                    active ? 'bg-slate-50 text-slate-900' : 'text-slate-600',
                    item.danger && 'text-red-600 hover:text-red-700',
                  )}
                  onClick={(event) => {
                    event.stopPropagation()
                    item.onSelect()
                  }}
                >
                  {item.icon ? <span className="h-4 w-4">{item.icon}</span> : null}
                  <span>{item.label}</span>
                </button>
              )}
            </Menu.Item>
          ))}
        </Menu.Items>
      </Transition>
    </Menu>
  )
}

export default KebabMenu
